<template>
  <div>
    <h2>用户管理</h2>
    <el-table v-if="!loading" :data="users" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column label="角色">
        <template #default="scope">
          <el-tag v-for="role in scope.row.roles" :key="role.id" style="margin-right: 5px;">
            {{ role.name }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-else-if="error" :description="error.message" />
    <el-empty v-else description="加载中..." />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

const USERS_QUERY = gql`
  query {
    users {
      id
      username
      createTime
      updateTime
      roles {
        id
        name
      }
    }
  }
`

const { result, loading, error } = useQuery(USERS_QUERY)

const users = ref([])

watch(result, (newResult) => {
  if (newResult && newResult.users) {
    users.value = newResult.users
  }
})

onMounted(() => {
  if (result.value && result.value.users) {
    users.value = result.value.users
  }
})
</script>